//###############
//FILE : FireServersCommand.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############
package oop.ex3.filemanager;

import oop.ex3.communication.SocketAddress;
import oop.ex3.protocol.sessions.FileGoAwaySession;

/**
 * Implements the FIRESERVERS command as specified in the assignment.
 * @author daniel
 */
public class FireServersCommand extends UserCommand {
    private static final String FIRE_COMMAND = "FIRESERVERS";

    private NameServerConnection _connection;
    private NameServerDatabase _nameServers;

    /**
     * Construct a new fireservers command with a connection that it can use
     * to connect to NSs.
     * @param connection The NS connection to use.
     */
    public FireServersCommand(NameServerConnection connection) {
        super(FIRE_COMMAND);
        _connection = connection;
        _nameServers = connection.getNameServerDatabase();
    }

    private void fireServer(SocketAddress nameServer) {
        if (!_connection.initializeStreams(nameServer))
            return;

        FileGoAwaySession session = new FileGoAwaySession();
        _connection.initializeSession(session);
        session.executeSession(_connection.getInputStream(), _connection.getOutputStream());

        _connection.closeConnection();
    }


    @Override
    public boolean executeCommand(String command) {
        for (SocketAddress nameServer : _nameServers.getAddressList())
            fireServer(nameServer);
        return true;
    }

}
